package Demo;

import java.util.concurrent.PriorityBlockingQueue;


//描述一个任务
class MyTake implements Comparable<MyTake>{
    private Runnable runnable;
    private long time;

    public MyTake(Runnable runnable,long times) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + times;
    }

    //形成多态
    public void run() {
        runnable.run();
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTake o) {
        return (int)(this.time - o.time);
    }
}

class MyTimer {
    Object object = new Object();
    PriorityBlockingQueue<MyTake> que =  new PriorityBlockingQueue<>();

    public void schedule(Runnable runnable,long timer) {
        MyTake myTake = new MyTake(runnable,timer);
        synchronized(object) {
            //有新任务的时候唤醒,防止新任务的等待时间比现有任务短,需要调整执行时间
            que.put(myTake);
            object.notify();
        }
    }

    public MyTimer() {
        Thread t = new Thread(() -> {
           while(true) {
               synchronized (object) {
                   try {
                       //为空的时候会陷入阻塞,这时候如果不释放锁会形成死锁
                       while(que.isEmpty()) {
                           object.wait();
                       }
                       long times = System.currentTimeMillis();
                       MyTake myTake = que.take();
                       if (myTake.getTime() > times) {
                           que.put(myTake);
                           //防止空转
                           long time = myTake.getTime() - times;
                           object.wait(time);
                       } else {
                           myTake.run();
                       }
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
               }
           }
        });

        t.start();
    }
}
public class Main {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1111");
            }
        }, 1000);


        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2222");
            }
        }, 3000);


        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("3333");
            }
        }, 2000);
    }
}
